import React, {Component} from 'react';
import {connect} from 'dva';
import {routerRedux} from 'dva/router'

import {dataCalc} from './dataCalc'
import style from './home.less'
import {Tabtitle,NoData,InfoList} from '../../../components'

import moment from 'moment';
import {Row,Col,Card,DatePicker,Select,Table,Pagination,Button,Modal,Form,Input} from 'antd'

import PieCharts from '../components/PieCharts'
import SectionBox from '../components/SectionBox'
import TableList from '../components/TableList'

// 下拉框 组件
const Option = Select.Option
const SelectBox=({
  label='label',
  data=[
    {
      name:'全部',
      value:'all'
    },
    {
      name:'成功',
      value:'1'
    },
    {
      name:'失败',
      value:'0'
    }
  ],
  value='all',
  style={
    width: 120
  },
  handleChange,
  })=>{
  const myProps = {
    defaultValue:value,
    value:value,
    style,
    onChange(value){
      handleChange(value)
    }
  }

  return (
    <div>
      <label>{ label }：</label>
      <Select { ...myProps }>
        {
          data.map((item,i)=><Option value={item.value} key={i}>{item.name}</Option>)
        }
      </Select>
    </div>
  )
}

const ToolBar=({
  data,
  filter,
  handleChange,
  })=>{
  const myProps={
    label:'任务',
    data,
    value:filter,
    style:{
      width:200,
      margin:'5px 0'
    },
    handleChange(value){
      handleChange(value)
    }
  }
  return(
    <div className="toolbar">
      <SelectBox {...myProps} />
    </div>
  )
}

// 基本信息
const BaseInfo=({
  data = [],
  })=>{
  const cardProps={
    title:'基础信息',
    bordered:false,
    noHovering:true,
  }
  const infoProps={
    data
  }
  return (
    <section className='baseInfo'>
      <Card {...cardProps}>
        <InfoList {...infoProps} />
      </Card>
    </section>
  )
}

// 错误分布
const ErrorDistribution=({
  data = [],
  })=>{
  const cardProps={
    title:'错误分布',
    bordered:false,
    noHovering:true,
  }
  const pieProps={
    data
  }
  return (
    <section className='errorDistribution'>
      <Card {...cardProps}>
        <PieCharts {...pieProps} />
      </Card>
    </section>
  )
}


// 执行记录 模块
const HistoryRecords=({
  filter,
  data=[],
  jobID,
  handleChange,
  queryDetail,
  })=>{
  const selectProps={
    label:'状态',
    value:filter,
    handleChange(value){
      handleChange(value)
    }
  }
  const cardProps={
    title:'执行记录',
    bordered:false,
    noHovering:true,
    extra:<SelectBox {...selectProps}/>,
  }
  const tableProps={
    dataSource: data,
    columns : [
      {
        title: '开始时间',
        dataIndex: 'startTime',
        key: 'startTime',
      },{
        title: '结束时间',
        dataIndex: 'endTime',
        key: 'endTime',
      }, {
        title: '执行地址',
        dataIndex: 'location',
        key: 'location',
      }, {
        title: '执行结果',
        dataIndex: 'status',
        key: 'status',
        render: (text, row, index) =>text==='1'?<span style={{color:'green'}}>成功</span>:<span style={{color:'red'}}>失败</span>,
      }, {
        title: '错误类型',
        dataIndex: 'type',
        key: 'type',
      }, {
        title: '建议对策',
        dataIndex: 'suggest',
        key: 'suggest',
      }
    ],
    key:'key',
    size:"small",
    bordered:true,
    pagination:{
      pageSize:15,
    },
    rowClassName:(record, index)=>record.id === jobID ? "on" : '',
    onRowClick(record, index, event){
      queryDetail(record)
    }
  }
  return(
    <section className='historyRecords'>
      <Card {...cardProps}>
        <Table {...tableProps}/>
      </Card>
    </section>
  )
}

// 运行概要
const RunningSummary=({
  data = [],
  })=>{
  const cardProps={
    title:'运行概要',
    bordered:false,
    noHovering:true,
  }
  const infoProps={
    data
  }
  return (
    <section className='runningSummary'>
      <Card {...cardProps}>
        <InfoList {...infoProps} />
      </Card>
    </section>
  )
}

// 错误详情
const ErrDetails=({
  data = '',
  })=>{
  const cardProps={
    title:'错误详情',
    bordered:false,
    noHovering:true,
  }
  return (
    <section className='errTip'>
      <Card {...cardProps}>
        <div className="inner">
          {data}
        </div>
      </Card>
    </section>
  )
}

// 检查详情（取数类任务）
const CheckDetailsValue=({
  data=[],
  })=>{
  const cardProps={
    title:'检查详情(取数类任务)',
    bordered:false,
    noHovering:true,
  }
  const tableProps={
    dataSource: data,
    columns : [
      {
        title: '源SQL',
        dataIndex: 'sourceSql',
        key: 'sourceSql',
      }, {
        title: '源量',
        dataIndex: 'sourceNum',
        key: 'sourceNum',
      }, {
        title: '目标量',
        dataIndex: 'targetNum',
        key: 'targetNum',
      }, {
        title: '目标SQL',
        dataIndex: 'targetSql',
        key: 'targetSql',
      }
    ],
    key:'sourceSql',
    size:"small",
    bordered:true,
    pagination:false
  }
  return(
    <section className='checkDetailsValue'>
      <Card {...cardProps}>
        <Table {...tableProps}/>
      </Card>
    </section>
  )
}

// 检查详情(后台计算类任务)
const CheckDetailsCalc=({
  data=[],
  })=>{
  const cardProps={
    title:'检查详情(后台计算类任务)',
    bordered:false,
    noHovering:true,
  }
  const tableProps={
    dataSource: data,
    columns : [
      {
        title: '预计值',
        dataIndex: 'expect',
        key: 'expect',
      }, {
        title: '实际值',
        dataIndex: 'actual',
        key: 'actual',
      }, {
        title: '误差内容',
        dataIndex: 'content',
        key: 'content',
      }
    ],
    key:'expect',
    size:"small",
    bordered:true,
    pagination:false
  }
  return(
    <section className='checkDetailsCalc'>
      <Card {...cardProps}>
        <Table {...tableProps}/>
      </Card>
    </section>
  )
}

// 处理记录 添加
const ProcessingRecordExtra=({
  data='添加',
  openAddRecordModal,
  })=>{
  const btnProps={
    onClick(){
      openAddRecordModal()
    }
  }
  return (
    <div>
      <Button {...btnProps}>{data}</Button>
    </div>
  )
}

// 处理记录 模态框
const FormItem=Form.Item
const ProcessingRecordModal=Form.create()((props)=>{
  const { visible, onCancel, onCreate, form, jobID,addRecord,closeAddRecordModal,} = props;
  const { getFieldDecorator } = form;
  const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };

  const modalProps={
    title:"添加处理记录",
    visible:true,
    onOk(e) {
      form.validateFields((err, values) => {
  			if (err) {
  				return false;
  			}
        addRecord(values)

  		});

    },
    onCancel() {
      closeAddRecordModal()
    }
  }

  return(
      <Modal {...modalProps}>
        <Form layout="vertical" className={style.modalBox}>
            <FormItem {...formItemLayout} label="处理人：">
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入处理人!' }],
              })(
                <Input />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="处理时间：">
              {getFieldDecorator('date', {
                rules: [{ required: true, message: '请选择处理时间!' }],
              })(
                <DatePicker showTime format="YYYY-MM-DD HH:mm:ss"/>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="处理结果：">
              {getFieldDecorator('result', {
                rules: [{ required: true, message: '请输入处理结果!' }],
              })(
                <Input />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="操作内容：">
              {getFieldDecorator('content')(<Input type="textarea" />)}
            </FormItem>

          </Form>
      </Modal>
  )
})

// 处理记录 模块
const ProcessingRecord=({
  data=[],
  jobID,
  showModal=false,
  openAddRecordModal,
  addRecord,
  closeAddRecordModal,
  })=>{
  const cardProps={
    title:'处理记录',
    bordered:false,
    noHovering:true,
    extra:<ProcessingRecordExtra data='添加' openAddRecordModal={openAddRecordModal} />,
  }
  const tableProps={
    dataSource: data,
    columns : [
      {
        title: '处理人',
        dataIndex: 'name',
        key: 'name',
      }, {
        title: '处理时间',
        dataIndex: 'date',
        key: 'date',
      }, {
        title: '处理结果',
        dataIndex: 'result',
        key: 'result',
      }, {
        title: '操作内容',
        dataIndex: 'content',
        key: 'content',
      }
    ],
    key:'name',
    size:"small",
    bordered:true,
    pagination:{
      pageSize:30,
    }
  }
  return(
    <section className='record'>
      <Card {...cardProps}>
        <Table {...tableProps}/>
      </Card>
      {
        showModal?<ProcessingRecordModal jobID={jobID} addRecord={addRecord}/>:null
      }
    </section>
  )
}

// 任务执行报告
const SchedulingDetails = ({dispatch,schedulingDetails,location}) =>{
  const tag = 'schedulingDetails'

  const {
    filter,
    showModal,
		jobInfo,
    jobID,
    jobName,
		errorDistribute,
		jobHistoryAll,
		jobHistory,
    records,
    jobList,
    }=schedulingDetails

  const dataConfig = dataCalc({
      ...schedulingDetails,
      dispatch,
      location,
      tag,
    })
  const {
    jobListData,
    baseInfoData,
    errorData,
    failListData,
    historyData,
    errTip,
    valueData,
    calcData,
    recordData,
    } = dataConfig
  // 筛选任务
  const filterJobName=(value)=>{
    dispatch({
      type:`${tag}/changeRouter`,
      payload:{
        pathname:location.pathname,
        query:{
          jobName:value
        }
      }
    })
  }

  // 筛选结果类型
  const filterResultStatus=(value)=>{
    dispatch({
      type:`${tag}/filterData`,
      payload:{
        filter:value
      }
    })
  }

  // 查询详情
  const queryDetail=(record)=>{
    dispatch({
      type:`${tag}/getDetails`,
      payload:{
        jobID:record.id
      }
    })
  }

  // 打开新增处理结果模态框
  const openAddRecordModal=()=>{
    dispatch({
      type:`${tag}/setState`,
      payload:{
        showModal:true,
      }
    })
  }

  // 关闭新增处理结果模态框
  const closeAddRecordModal=()=>{
    dispatch({
      type:`${tag}/setState`,
      payload:{
        showModal:false,
      }
    })
  }

  // 新增处理结果
  const addRecord=(values)=>{
    dispatch({
      type:`${tag}/addJobHandling`,
      payload:{
        'jobID':jobID,
        'time':moment(values.date).format('YYYY-MM-DD HH:mm:ss'),
        'person':values.name,
        'content':values.content,
        'result':values.result,
      }
    })
    closeAddRecordModal()
  }


  return (
      <div className={`${style.schedulingDetails}`}>
        <Tabtitle value={'任务执行报告'}/>
        <div className="content-inner">
          <Row>
            <Col>
              <ToolBar data={jobListData} filter={jobName||''} handleChange={filterJobName} />
            </Col>
          </Row>
          {
            jobName?(
              <div className="contentMain">
                <div style={{paddingBottom:'20px',borderBottom:'10px #fff solid'}}>
                  <Row gutter={10} >
                    <Col span={8}>
                      <BaseInfo data={baseInfoData} />
                    </Col>
                    <Col span={16}>
                      <ErrorDistribution data={errorData} />
                    </Col>
                  </Row>
                </div>
                <Row gutter={10}>
                  <Col span={14}>
                    <HistoryRecords filter={filter} data={failListData} jobID={jobID}
                      handleChange={filterResultStatus}
                      queryDetail={queryDetail}
                    />
                  </Col>
                  <Col span={10} className={style.details}>
                    <RunningSummary data={historyData}/>
                    <ErrDetails data={errTip} />
                    {
                      jobInfo&&jobInfo.jobType==="取数类"?<CheckDetailsValue data={valueData} />:<CheckDetailsCalc data={calcData} />
                    }
                    <ProcessingRecord data={recordData} jobID={jobID} showModal={showModal} dispatch={dispatch} tag={tag}
                      openAddRecordModal={openAddRecordModal}
                      addRecord={addRecord}
                      closeAddRecordModal={closeAddRecordModal}
                    />
                  </Col>
                </Row>
              </div>
            ):(
              <div className="contentMain">
                <NoData />
              </div>
            )
          }

        </div>
      </div>
    )

}

SchedulingDetails.propTypes = {
};

export default connect(({schedulingDetails}) => ({schedulingDetails}))(SchedulingDetails);
